﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web.Hosting;
using System.Web.WebPages;
using Eksponent.RazorRocks.Helpers;

namespace Eksponent.RazorRocks
{
    public class RazorTemplateAction<TItem> : TemplateAction<TItem>
    {
        public const string ItemKey = "RazorRocks.Item",
                            ReturnValueKey = "RazorRocks.ReturnValues",
                            CallParametersKey = "RazorRocks.CallParameters";

        /// <summary>
        /// Gets or sets the name of the template.
        /// </summary>
        /// <value>
        /// The name of the template.
        /// </value>
        public string TemplateName { get; set; }

        /// <summary>
        /// Gets or sets the render parameters to be passed to the template.
        /// </summary>
        /// <value>
        /// The render parameters.
        /// </value>
        public object RenderParameters { get; set; }


        public RazorTemplateAction(string templateName, object renderParameters = null)
        {
            TemplateName = templateName;
            RenderParameters = renderParameters;
        }

        public override TemplateHelperResult Render(TItem item, TemplateRenderContext<TItem> context)
        {
            var pathBuilder = new StringBuilder(context.BasePath);
            if (!string.IsNullOrEmpty(context.Subfolder))
            {
                pathBuilder.Append(context.Subfolder).Append("/");
            }
            pathBuilder.Append(TemplateName);
            if( !TemplateName.EndsWith(".cshtml") )
            {
                pathBuilder.Append(".cshtml");
            }

            var path = "" + pathBuilder;
            if (context.FileCache.GetOrInitialize(path, () => File.Exists(HostingEnvironment.MapPath(path))))
            {
                var parameters = context.Parameters;                
                foreach (var kv in RenderParameters.AsDictionary())
                {                                        
                    if (!parameters.ContainsKey(kv.Key))
                    {
                        parameters[kv.Key] = kv.Value;
                    }
                }

                var returnValues = new Dictionary<string, object>();

                parameters[ItemKey] = item;
                parameters[ReturnValueKey] = new DynamicDictionary(returnValues);
                parameters[CallParametersKey] = parameters;

                var page = (WebPageBase)WebPageContext.Current.Page;
                return
                    new TemplateHelperResult(w =>
                                             page.RenderPage(path, context.Parameters).WriteTo(w), returnValues);
            }

            return null;
        }


        public override string ToString()
        {
            return TemplateName;
        }
    }
}